package com.hushan.elevator.websocket.server;

import com.hushan.elevator.model.DeviceInfo;
import com.hushan.elevator.service.DeviceInfoService;
import com.hushan.elevator.service.DeviceLogService;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Data
@Slf4j
@ServerEndpoint("/ws/{id}")
public class DeviceSocketServer {

    public static CopyOnWriteArraySet<DeviceSocketServer> sessionSet = new CopyOnWriteArraySet<>();
    private Session session;
    public static DeviceInfoService deviceInfoService;
    public static DeviceLogService deviceLogService;
    DeviceInfo deviceInfo = null;
    private String id;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) throws Exception {

        deviceInfo = deviceInfoService.findBySerialNumb(id);
        this.session = session;
        this.id = id;
        sessionSet.add(this);

        if(Objects.nonNull(deviceInfo)) {
            log.info("ws 连接设备：【{}】", deviceInfo);
            deviceLogService.onConnect(deviceInfo);
        } else {
            log.error("ws 连接设备不存在，需要在系统中添加设备");
        }
    }

    // 长连接断开时触发
    @OnClose
    public void onClose() {
        sessionSet.remove(this);
        log.info("断开连接 {} close", deviceInfo);
        deviceLogService.onDisConnect(deviceInfo);
    }

    // 长连接异常时触发
    @OnError
    public void onError(Session session, Throwable error, @PathParam("id") String id) {
        log.error(String.valueOf(error));
        if (sessionSet.remove(this)) {
            error.printStackTrace();
        }

        log.warn("device {} error {}", id, error.toString());
        deviceLogService.onError(deviceInfo.getSerialNumber(), "服务器连接出现异常", error.toString());
    }

    // receive msg from device
    // to web socket
    @OnMessage
    public void onMessage(ByteBuffer message, Session session) throws Exception {
        byte[] bytes = new byte[message.remaining()];
        message.get(bytes);
        // online
        String string = new String(bytes);
        WebSocketServer.sendMessage(this.id, string);

        deviceLogService.onMessage(deviceInfo, string);
    }

    // send msg
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public synchronized static void sendMessage(@PathParam("id") String id, String message) throws IOException {
        for (DeviceSocketServer ws : sessionSet) {
            if (ws.id.equals(id)) {
                ws.sendMessage(message);
            }
        }
    }

}
